package com.mamahao.vmnetframework.framework.net.datasource.impl

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.OnLifecycleEvent
import android.text.TextUtils
import android.util.Log
import com.mamahao.vmnetframework.framework.net.basis.RetrofitManagement
import com.mamahao.vmnetframework.framework.net.basis.callback.RequestMultiplyCallback
import com.mamahao.vmnetframework.framework.net.basis.code.HttpCode
import com.mamahao.vmnetframework.framework.net.basis.exception.ConnectionException
import com.mamahao.vmnetframework.framework.net.basis.exception.ResultInvalidException
import com.mamahao.vmnetframework.framework.net.basis.exception.base.BaseException
import com.mamahao.vmnetframework.framework.net.datasource.ISimpleDataSource
import com.mamahao.vmnetframework.framework.net.service.MMHService
import kotlinx.coroutines.*
import retrofit2.HttpException
import java.net.ConnectException
import kotlin.Exception
import kotlin.coroutines.CoroutineContext

/**
 * 发起网络请求管理类
 */
class SimpleSourceImpl : ISimpleDataSource,CoroutineScope {

    private val job = SupervisorJob()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun getService(): MMHService {
        return RetrofitManagement.getInstance().getService(MMHService::class.java)
    }

    override fun getService(host: String): MMHService {
        if(TextUtils.isEmpty(host)){
            return RetrofitManagement.getInstance().getService(MMHService::class.java)
        }
        return RetrofitManagement.getInstance().getService(MMHService::class.java,host)
    }

    override fun <T> execute(deferred: Deferred<T>, callback: RequestMultiplyCallback<T>) {

        launch {
            try {
                callback.onSuccess(withContext(Dispatchers.IO) { deferred }.await())
            } catch (e: ConnectException) {
                //网络异常
                callback.onFail(ConnectionException())
            } catch (e: HttpException){
                //http网络异常
                callback.onFail(ConnectionException())
            } catch (e: ResultInvalidException){
                //无效请求
                callback.onFail(ResultInvalidException())
            } catch (e:Exception){
                //冗余捕获
                callback.onFail(BaseException(HttpCode.CODE_UNKNOWN,e.message?:"未知异常"))
            }
        }
    }

    override fun onDestory() {
        coroutineContext.cancelChildren()
    }

}